<?php

/**
 * 获取策略决策结果
 */

use Upfor\UpforPHP\Library\Curl\Curl;

require_once __DIR__ . '/../UpforPHP/bootstrap.php';
require_once __DIR__ . '/../vendor/autoload.php';

$startTime = date("Y-m-d H:i:s");
$today = date('Y-m-d');

$logDir = LOG_DIR . "/script_log";
if (!file_exists($logDir)) {
    @mkdir($logDir, 0777, true);
}

file_put_contents("{$logDir}/{$today}policy.log", "--script start at:" . $startTime . "--\n", FILE_APPEND);

$list = getPlatDomainPolicyDecision();

file_put_contents("{$logDir}/{$today}policy.log", json_encode($list), FILE_APPEND);

foreach ($list['data'] as $l_val) {
    $plat_domain_id = $l_val['platform_domain_id'];
    $info = model('PlatDomain')->getRow('subzone,domain', ['plat_domain_id' => $plat_domain_id]);
    foreach ($l_val['views'] as $view_val) {
        $recordList = array();

        $ips = explode(',', $view_val['ip']);
        $plat_domain_line_id = $view_val['view_id'];
        $viewInfo = model('PlatDomainLine')->getRow('plat_domain_line_id, record_line_id,record_type,record_line_name,points,ttl,status', ['plat_domain_line_id' => $plat_domain_line_id]);
        if ($info && $viewInfo) {
            $ip_num = 0;
            $old_ips = $viewInfo['points'] ? json_decode($viewInfo['points'], true) : '';
            foreach ($ips as $ip) {
                if ($old_ips && in_array($ip, $old_ips)) {
                    $ip_num++;
                }
                $recordList[$ip] = array(
                    'subDomain'  => $info['subzone'],
                    'recordType' => $viewInfo['record_type'],
                    'recordLine' => $viewInfo['record_line_name'],
                    'record'     => $ip,
                    'ttl'        => $viewInfo['ttl'],
                );
            }
            if ( $ip_num && count($old_ips) == $ip_num && $ip_num == count($ips) ) {
                continue;
            }
            model('PlatDomainSubRecord')->updateSubrecord('script:policyDecision', $plat_domain_line_id, $recordList);
            $time = time();
            $update_info = array(
                'points'           => json_encode($ips),
                'update_time'      => $time,
                'status'           => 1
                );
            $id = model('PlatDomainLine')->update($update_info, ['plat_domain_line_id'=>$plat_domain_line_id]);
        }
    }
}

$endTime = date("Y-m-d H:i:s");
file_put_contents("{$logDir}/{$today}policy.log", "\n --script end at:{$endTime}--\n\n", FILE_APPEND);

/**
 * 获取平台域名策略决策结果
 */
function getPlatDomainPolicyDecision() {
    $message = '获取平台域名策略决策结果错误';
    //发起curl get请求
    $curl = new Curl();
    $curl->setTimeout(30);
    $curl->get(config(null, 'outApi')['getPlatDomainPolicyDecisionURL']);
    $time = date("Y-m-d H:i:s");
    //curl错误记录日志
    if ($curl->error) {
        $errorInfo = $time . ' -> '.$curl->errorCode . ' : ' . $curl->errorMessage;
        echo $errorInfo."\n";
    }
    $curl->close();
    $data = @json_decode($curl->rawResponse, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo $time . ' -> '.$message.' json格式错误';
    }
    if (!isset($data['code']) || $data['code'] != 0) {
        echo $time . ' -> '.$message.' code:'.$data['code'].' msg:'.$data['msg'] ;
    }

    return $data;
}